/*
 * Queue.c
 *
 *  Created on: 2011-5-22
 *      Author: william nie
 */

#include"Queue.h"

Status InitQueue(Queue **queue) {
	(*queue) = (Queue*)malloc(sizeof(Queue));

	QNode *qNode = (QNode*) malloc(sizeof(QNode));

	(*queue)->front = (*queue)->rear = qNode;
	(*queue)->front->next = NULL;
	(*queue)->length = 0;
	(*queue)->size = sizeof(QNode);

	return OK;
}

Status DestroyQueue(Queue **queue) {

	while ((*queue)->front != NULL) {
		(*queue)->rear = (*queue)->front->next;
		free((*queue)->front);
		(*queue)->front = (*queue)->rear;
	}

	free(*queue);
	(*queue) = NULL;

	return OK;

}

Status ClearQueue(Queue *queue) {

	while (queue->front != NULL) {
		queue->rear = queue->front->next;
		free(queue->front);
		queue->front = queue->rear;
	}

	queue->front = queue->rear = (QNode*)malloc(sizeof(QNode));

	queue->length = 0;
	queue->size = sizeof(QNode);

	return OK;
}

BOOL QueueEmpty(Queue *queue) {
	if(queue->length==0){
		return TRUE;
	}
	return FALSE;
}

int QueueLength(Queue *queue) {
	return queue->length;
}

QNode* GetHead(Queue *queue) {
	return queue->front->next;
}

Status EnQueue(Queue *queue, QElemType *node) {
	QNode *newNode = (QNode*)malloc(sizeof(QNode));
	newNode->data = node;
	newNode->next = NULL;

	queue->rear->next = newNode;
	queue->rear = queue->rear->next;

	queue->length += 1;
	queue->size += sizeof(QNode);

	return OK;
}

QElemType* DeQueue(Queue *queue) {

	if(QueueEmpty(queue)==TRUE){
		return NULL;
	}

	QNode *qNode = queue->front->next;
	QElemType *toReturn = qNode->data;

	queue->front->next = qNode->next;
	free(qNode);

	queue->length -= 1;
	queue->length -= sizeof(QNode);

	return toReturn;
}

Status QueueTraverse(Queue *queue, QueueVisit visit) {
	QNode *qNode = queue->front->next;
	int i = 0;

	if(queue->front==queue->rear){
		printf("Queue is empty.");
	}

	for( ; i < queue->length ; ++i){
		if(visit(qNode)==FALSE){
			return ERROR;
		}
		qNode = qNode->next;
	}
	return OK;
}

BOOL DefaultQueueVisit(QNode *qNode){
	printf("%d ",*(qNode->data));
	return TRUE;
}

Status FillQueue(Queue *queue){
	printf("Fill The Queue With Integer Value.\n");

	QElemType *data = (QElemType*)malloc(sizeof(QElemType));

	while(scanf("%d",data)){
		EnQueue(queue,data);
		data = (QElemType*)malloc(sizeof(QElemType));
	}

	printf("Fill Queue Complete.\n\n");

	return OK;
}
